import { Elysia } from 'elysia';
import { cors } from '@elysiajs/cors';
import { swagger } from '@elysiajs/swagger';
import { staticPlugin } from '@elysiajs/static';
import { authRoutes } from './routes/auth';
import { productRoutes } from './routes/products';
import { caseRoutes } from './routes/cases';
import { tagRoutes } from './routes/tags';

import { uploadRoutes } from './routes/upload.js';
import { settingsRoutes } from './routes/settings.js';
import { dashboardRoutes } from './routes/dashboard.js';

import { backupRoutes } from './routes/backup';
import { logRoutes } from './routes/logs';
import { userRoutes } from './routes/users';
import { contactRoutes } from './routes/contacts';
import { initDatabase } from './db/init';
import { ensureUploadDir, cleanupTempFiles } from './middleware/upload';
import { apiLoggerMiddleware } from './middleware/logger';
import { handleApiError } from './utils/response';
import { autoBackup } from './scripts/backup-database';
import { Logger } from './utils/response';

const app = new Elysia()
  // 日志中间件
  .use(apiLoggerMiddleware())
  
  // CORS 配置
  .use(cors({
    origin: process.env.NODE_ENV === 'production' 
      ? ['https://cxgg.com', 'https://www.cxgg.com']
      : true,
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
  }))
  
  // Swagger API 文档
  .use(swagger({
    documentation: {
      info: {
        title: '中山财兴广告 API',
        version: '1.0.0',
        description: '中山财兴广告官网后端 API 文档'
      },
      tags: [
        { name: 'Auth', description: '认证相关接口' },
        { name: 'Dashboard', description: '仪表盘统计接口' },
        { name: 'Products', description: '产品管理接口' },
        { name: 'Cases', description: '案例管理接口' },
        { name: 'Tags', description: '标签管理接口' },

        { name: 'Upload', description: '文件上传接口' },
        { name: 'Settings', description: '系统设置接口' },
        { name: 'Backup', description: '数据备份接口' },
        { name: 'Logs', description: '系统日志接口' },
        { name: 'Users', description: '用户管理接口' }
      ]
    }
  }))
  
  // 静态文件服务
  .use(staticPlugin({
    assets: 'uploads',
    prefix: '/uploads'
  }))
  
  // 健康检查
  .get('/health', () => ({
    status: 'ok',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  }))
  
  // API 路由
  .group('/api', (app) =>
    app
      .use(authRoutes)
      .use(productRoutes)
      .use(caseRoutes)
      .use(tagRoutes)
      .use(uploadRoutes)
      .use(settingsRoutes)
      .use(dashboardRoutes)

      .use(backupRoutes)
      .use(logRoutes)
      .use(userRoutes)
      .use(contactRoutes)
      // 兼容性路由
      .get('/case-categories', async () => {
        const { getCaseCategories } = await import('./controllers/settingsController');
  return getCaseCategories({} as any);
      })
      .get('/product-categories', async () => {
        const { getProductCategories } = await import('./controllers/settingsController');
        return getProductCategories({} as any);
      })
  )
  
  // 全局错误处理
  .onError(handleApiError)
  
  // 404 处理
  .all('*', ({ set }) => {
    set.status = 404;
    return {
      success: false,
      message: '接口不存在'
    };
  });

const port = process.env.PORT || 3001;

app.listen(port, async () => {
  // 初始化数据库
  await initDatabase();
  Logger.info('Database initialized');

  // 初始化上传目录
  await ensureUploadDir();
  Logger.info('Upload directories initialized');

  // 启动时清理临时文件
  await cleanupTempFiles();
  Logger.info('Temporary files cleaned up');

  // 设置定时清理任务（每24小时执行一次）
  setInterval(async () => {
    Logger.info('Running scheduled cleanup...');
    await cleanupTempFiles();
    Logger.info('Scheduled cleanup completed');
  }, 24 * 60 * 60 * 1000); // 24小时

  // 定时数据库备份（每天凌晨2点执行）
  const scheduleBackup = () => {
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(2, 0, 0, 0);
    
    const msUntilBackup = tomorrow.getTime() - now.getTime();
    
    setTimeout(() => {
      autoBackup().catch(err => Logger.error('Auto backup failed:', err));
      // 设置每24小时执行一次
      setInterval(() => {
        autoBackup().catch(err => Logger.error('Auto backup failed:', err));
      }, 24 * 60 * 60 * 1000);
    }, msUntilBackup);
    
    Logger.info('数据库备份已安排在每天凌晨2点执行');
  };

  scheduleBackup();

  Logger.info(`Server is running on http://localhost:${port}`);
  Logger.info(`API Documentation: http://localhost:${port}/swagger`);
  Logger.info(`Health Check: http://localhost:${port}/health`);
  
  // 打印所有可用路由
  Logger.info('Available API Routes:');
  Logger.info('├── GET    /health');
  Logger.info('├── GET    /swagger');
  Logger.info('├── GET    /uploads/*');
  Logger.info('│');
  Logger.info('├── 🔐 Auth Routes (/api/auth):');
  Logger.info('│   ├── POST   /api/auth/login');
  Logger.info('│   ├── POST   /api/auth/logout');
  Logger.info('│   └── GET    /api/auth/profile');
  Logger.info('│');
  Logger.info('├── 📊 Dashboard Routes (/api/dashboard):');
  Logger.info('│   ├── GET    /api/dashboard/stats');
  Logger.info('│   ├── GET    /api/dashboard/monthly');
  Logger.info('│   └── GET    /api/dashboard/system-status');
  Logger.info('│');
  Logger.info('├── 🛍️  Product Routes (/api/products):');
  Logger.info('│   ├── GET    /api/products');
  Logger.info('│   ├── GET    /api/products/categories');
  Logger.info('│   ├── GET    /api/products/:id');
  Logger.info('│   ├── POST   /api/products');
  Logger.info('│   ├── PUT    /api/products/:id');
  Logger.info('│   └── DELETE /api/products/:id');
  Logger.info('│');
  Logger.info('├── 📁 Case Routes (/api/cases):');
  Logger.info('│   ├── GET    /api/cases');
  Logger.info('│   ├── GET    /api/cases/categories');
  Logger.info('│   ├── GET    /api/cases/:id');
  Logger.info('│   ├── POST   /api/cases');
  Logger.info('│   ├── PUT    /api/cases/:id');
  Logger.info('│   └── DELETE /api/cases/:id');
  Logger.info('│');
  Logger.info('├── 🏷️  Tag Routes (/api/tags):');
  Logger.info('│   ├── GET    /api/tags');
  Logger.info('│   ├── GET    /api/tags/stats');
  Logger.info('│   ├── GET    /api/tags/:id');
  Logger.info('│   ├── POST   /api/tags');
  Logger.info('│   ├── PUT    /api/tags/:id');
  Logger.info('│   ├── DELETE /api/tags/:id');
  Logger.info('│   └── POST   /api/tags/batch-delete');
  Logger.info('│');

  Logger.info('├── 📤 Upload Routes (/api/upload):');
  Logger.info('│   └── POST   /api/upload');
  Logger.info('│');
  Logger.info('├── ⚙️  Settings Routes (/api/settings):');
  Logger.info('│   ├── GET    /api/settings');
  Logger.info('│   └── PUT    /api/settings');
  Logger.info('│');
  Logger.info('├── 💾 Backup Routes (/api/backup):');
  Logger.info('│   ├── GET    /api/backup');
  Logger.info('│   ├── POST   /api/backup');
  Logger.info('│   ├── GET    /api/backup/:id/download');
  Logger.info('│   ├── POST   /api/backup/:id/restore');
  Logger.info('│   └── DELETE /api/backup/:id');
  Logger.info('│');
  Logger.info('└── 📋 Log Routes (/api/logs):');
  Logger.info('    ├── GET    /api/logs');
  Logger.info('    ├── GET    /api/logs/stats');
  Logger.info('    ├── GET    /api/logs/export');
  Logger.info('    └── POST   /api/logs/cleanup');
  Logger.info('');
  Logger.info('🎯 系统功能:');
  Logger.info('├── ✅ 统一API响应格式');
  Logger.info('├── ✅ 集中错误处理');
  Logger.info('├── ✅ 接口访问日志记录');
  Logger.info('├── ✅ 数据备份与恢复');
  Logger.info('├── ✅ 系统日志管理');
  Logger.info('└── ✅ 自动定时任务');
  Logger.info('');
});

export default app;